<!--
 * @author guojiteng
 -->
<template>
  <div id="signcode">
    <div v-show="searchshow" class="signcode-search">
      <el-collapse-transition>
        <div v-show="searchshow" class="course-search merge">
          <span class="svg-container">
            <svg-icon icon-class="search" />
          </span>
          <el-input v-model.trim="listQuery.signName" placeholder="请输入签到名称搜索" class="search-input" />
          <div class="course-search-btn">
            <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
            <el-button class="filter-item" type="primary" @click="resettingBtn">重置</el-button>
            <span class="course-search-more" @click="searchshow = !searchshow">
              更多筛选条件
              <i class="el-icon-arrow-down" />
            </span>
          </div>
        </div>
      </el-collapse-transition>
    </div>

    <el-collapse-transition>
      <div v-show="!searchshow" class="course-search separate">
        <div class="course-search-inner">
          <el-row>
            <el-col :span="12">
              <div class="search-inner-item">
                <div class="item-label">签到描述</div>
                <el-input v-model.trim="search.remarks" style="width: 80%" class="filter-item" placeholder="请输入签到描述搜索" />
              </div>
            </el-col>
            <el-col :span="12">
              <div class="search-inner-item">
                <div class="item-label">签到名称</div>
                <el-input v-model.trim="search.signName" style="width: 80%" class="filter-item" placeholder="请输入签到名称搜索" />
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="course-search-btn">
          <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
          <el-button class="filter-item" type="primary" @click="resettingBtn">重置</el-button>
          <span class="course-search-more" @click="searchshow = !searchshow">
            精简筛选条件
            <i class="el-icon-arrow-up" />
          </span>
        </div>
      </div>
    </el-collapse-transition>

    <div class="btn-container">
      <div class="btn-container-title">
        <span>签到管理</span>
      </div>
      <div class="btn-container-btns">
        <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate">新建</el-button>
        <el-button class="filter-item" style="margin-left: 10px;" @click="handleDeletes">批量删除</el-button>
        <el-button class="filter-item" style="margin-left: 10px;" @click="back">返回</el-button>
      </div>
    </div>
    <div class="table">
      <my-table
        :list="list"
        tag="hnsign"
        operationwidth="80"
        :list-loading="listLoading"
        @handleSelectionChange="handleSelectionChange"
      >
        <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button type="text" size="mini" @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="text" size="mini" @click="handleCode(scope.row)">生成签到码</el-button>
            <el-button type="text" size="mini" @click="handleRecord(scope.row)">签到记录</el-button>
          </template>
        </el-table-column>
      </my-table>
    </div>
    <div class="btn-pagion fix">
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>
    <el-dialog v-el-drag-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" center width="600px">
      <el-form ref="dataForm" :model="temp" :rules="rules" class="dataForm" label-position="right" label-width="120px" style="height:250px">

        <el-form-item label="签到名称" prop="signName">
          <el-input v-model="temp.signName" placeholder="请输入签到名称" />
        </el-form-item>
        <el-form-item label="签到时间" prop="time">
          <el-date-picker
            v-model="temp.time"
            style="width: 100%;"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            clearable
            type="datetimerange"
            format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="签到描述" prop="remarks">
          <el-input
            v-model="temp.remarks"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4}"
            placeholder="请输入签到描述"
          />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" @click="dialogFormVisible = false">取消</el-button>
        <el-button style="padding: 8px 30px;" type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
    <!-- 二维码弹窗 -->
    <el-dialog v-el-drag-dialog title="签到码" :visible.sync="codeDialog" :close-on-click-modal="false" center width="600px">
      <div id="hnQrCord" ref="hnQrCord" />
      <div class="codeName">{{ codeName||'' }}</div>
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" @click="codeDialog = false">关闭</el-button>
        <el-button style="padding: 8px 30px;" type="primary" @click="download">下载</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { queryPage, insert, update, get, del } from '@/views/staffserve/ghhn/api/sign'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import permission from '@/directive/permission/index.js' // 权限判断指令
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import MyTable from '@/components/Table'
import QRCode from 'qrcodejs2'
export default {
  name: 'Signmanage',
  components: { Pagination, MyTable },
  directives: { permission, elDragDialog },
  data() {
    return {
      codeDialog: false,
      searchshow: true,
      codeName: '',
      multipleSelection: [],
      fileList: [],
      listQuery: {
        page: 1,
        limit: 10,
        signName: ''
      },
      search: {
        signName: '',
        remarks: ''
      },
      list: [],
      total: 0,
      dialogStatus: '',
      dialogFormVisible: false,
      textMap: {
        create: '新增签到',
        update: '编辑签到'
      },
      listLoading: true,
      temp: {
        matchmakerInfoId: '',
        signName: '',
        remarks: '',
        time: [],
        latitude: '',
        longitude: '',
        type: '4',
        checkllFlag: '0'
      },
      rules: {
        remarks: [{ required: true, message: '请输入签到描述', trigger: 'blur' }],
        signName: [{ required: true, message: '请输入签到名称称', trigger: 'blur' }],
        time: [{ required: true, message: '请选择签到时间', trigger: 'change' }]
      }
    }
  },
  created() {
    if (this.$route.query.i) {
      this.temp.matchmakerInfoId = this.$route.query.i
      this.getList()
    } else {
      this.$router.back()
    }
  },
  methods: {
    handleCode(row) {
      this.codeDialog = true
      this.$nextTick(() => {
        this.createQrCode(row)
      })
    },
    createQrCode(p) {
      document.getElementById('hnQrCord').innerHTML = ''
      var qrcode = new QRCode(this.$refs.hnQrCord, {
        text: `BA1:${this.$route.query.i}:${p.id}`,
        width: 200,
        height: 200,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H
      })
      this.codeName = p.signName
    },
    download() {
      const canvas = document.getElementById('hnQrCord').getElementsByTagName('canvas')
      const a = document.createElement('a')
      a.href = canvas[0].toDataURL('img/png')
      a.download = this.codeName + '的签到码'
      a.click()
    },
    back() {
      this.$router.replace({ path: this.$filterPath('index') })
    },
    handleSelectionChange(arr) {
      console.log('arr', arr)
      this.multipleSelection = arr
    },
    /**
     * 查询列表
     */
    getList(obj) {
      const _this = this
      var query = {
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit,
        matchmakerInfoId: this.$route.query.i
      }
      if (this.searchshow) {
        query['signName'] = this.listQuery.signName
      } else {
        query['signName'] = this.search.signName
        query['remarks'] = this.search.remarks
      }
      this.listLoading = true
      return new Promise((resolve, reject) => {
        queryPage(query).then(response => {
          this.list = response.data.data.rows
          this.total = response.data.data.total
          _this.listLoading = false
        }).catch(error => {
          reject(error)
          _this.listLoading = false
        })
      })
    },
    resetTemp() {
      this.temp.signName = ''
      this.temp.remarks = ''
      this.temp.time = ''
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resettingBtn() {
      this.listQuery.signName = ''
      this.listQuery.page = 1
      for (const i in this.search) {
        if (this.search['' + i + ''] instanceof Array) {
          this.search['' + i + ''] = []
        } else {
          this.search['' + i + ''] = ''
        }
      }
      this.getList()
    },

    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      if (row.id) {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        return new Promise((resolve, reject) => {
          get({ id: row.id }).then((res) => {
            loading.close()
            for (const i in this.temp) {
              if (i === 'time') {
                this.temp[i] = [res.data.data.startDatetime, res.data.data.endDatetime]
                this.temp['id'] = res.data.data.id
              } else {
                this.temp[i] = res.data.data[i]
              }
            }
            this.dialogStatus = 'update'
            this.dialogFormVisible = true
            this.$nextTick(() => {
              this.$refs['dataForm'].clearValidate()
            })
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      } else {
        this.$message({
          message: '获取数据失败！',
          type: 'warning'
        })
      }
    },

    getImg() {
      downImg({ id: this.temp.id }).then(res => {
        console.log('图片', res)
        const blob = new Blob([res.data], { type: 'image/jpg' })
        this.imageUrl = window.URL.createObjectURL(blob)
      }).catch(() => {
        this.$message.error('请求失败')
      })
    },
    handleDeletes() {
      if (this.multipleSelection.length == 0) {
        this.$message.error('请选择要删除的数据')
        return
      }
      const ids = this.multipleSelection.map((obj) => {
        return obj.id
      }).join(',')
      this.deleteData(ids)
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteData(row.id)
      }).catch(() => { })
    },
    handleRecord(row) {
      this.$router.push({ path: this.$filterPath('record'), query: { hi: this.$route.query.i, qi: row.id }})
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          return new Promise((resolve, reject) => {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            this.temp.id = ''
            const params = Object.assign({}, this.temp)
            params['startDatetime'] = this.temp.time && this.temp.time.length > 0 ? this.temp.time[0] : ''
            params['endDatetime'] = this.temp.time && this.temp.time.length > 0 ? this.temp.time[1] : ''
            delete params.time
            insert(params).then(response => {
              this.dialogFormVisible = false
              loading.close()
              this.getList()
              this.$message({
                message: '创建成功',
                type: 'success'
              })
            }).catch(error => {
              loading.close()
              reject(error)
            })
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const params = Object.assign({}, this.temp)
          params['startDatetime'] = this.temp.time && this.temp.time.length > 0 ? this.temp.time[0] : ''
          params['endDatetime'] = this.temp.time && this.temp.time.length > 0 ? this.temp.time[1] : ''
          delete params.time
          return new Promise((resolve, reject) => {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            update(params).then(response => {
              this.dialogFormVisible = false
              loading.close()
              this.getList()
            }).catch(error => {
              loading.close()
              reject(error)
            })
          })
        }
      })
    },
    deleteData(ids) {
      return new Promise((resolve, reject) => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        del({ ids: ids }).then(() => {
          loading.close()
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getList()
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" type="text/scss">
$dark_gray: #bfced6;
@import '@/styles/mixin.scss';
#signcode {
  padding: 10px;
  #hnQrCord
  {
    display: flex;
    justify-content: center;
  }
  .codeName{
    color: #000;
    display: flex;
    justify-content: center;
    margin:20px;
    font-size:28px;
    font-weight: 700;
  }
  .avatar-uploader .el-upload {
    margin-bottom: 10px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .el-upload__tip {
    margin-top: 0;
  }
  .avatar-uploader .el-upload {
    margin-bottom: 0;
    border: none;
  }
  .noImg {
    margin-left: 80px;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .imgavatar {
    width: 380px;
    height: 90px;
    display: block;
  }
  .avatar {
    height: 200px;
    width: 200px;
  }

  .signcode-search {
    background-color: #fff;
    .svg-container {
      padding: 0 5px 0 10px;
      color: $dark_gray;
      vertical-align: middle;
      display: inline-block;
      &_login {
        font-size: 20px;
      }
    }
    .search-input {
      width: 78%;
      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;
        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }
    .el-button.is-round {
      float: right;
      padding: 10px 30px;
    }
  }
  .course-search {
    background-color: #fff;
    padding: 0 10px;
    .svg-container {
      padding: 0 5px 0 10px;
      color: $dark_gray;
      vertical-align: middle;
      display: inline-block;
      &_login {
        font-size: 20px;
      }
    }
    .search-input {
      width: 50%;
      position: relative;
      &:after {
        content: '';
        position: absolute;
        left: -25px;
        right: 0;
        bottom: 8px;
        height: 1px;
        background: rgba(226, 227, 232, 1);
      }
      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;
        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }
    .course-search-btn {
      display: inline-block;
      float: right;
      .el-button.is-round {
        padding: 10px 30px;
        margin-right: 34px;
      }
      .course-search-more {
        font-size: 14px;
        font-weight: 500;
        @include font-color($mainColor);
        cursor: pointer;
        margin-left: 10px;
      }
    }
    &.merge {
      height: 50px;
      line-height: 50px;
    }
    &.separate {
      .course-search-inner {
        padding-top: 10px;
        .search-inner-item {
          .item-label {
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            color: #a6a6a6;
            font-weight: 400;
          }
          .el-input {
            position: relative;
            .el-input__inner {
              border: none;
              padding: 0;
            }
            &:after {
              content: '';
              height: 1px;
              background-color: #e2e3e8;
              position: absolute;
              left: 0;
              right: 0;
              bottom: 0;
            }
          }
        }
      }
      .course-search-btn {
        text-align: center;
        display: block;
        float: none;
        height: 56px;
        line-height: 56px;
      }
    }
  }
  .btn-container {
    display: flex;
    margin-top: 10px;
    .btn-container-title {
      flex: 1;
      height: 46px;
      line-height: 46px;
      font-size: 16px;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
    }
  }
}
</style>

